<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>交互式单词学习卡</title>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        /* 保持原有样式不变 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Inter', 'Segoe UI', system-ui, -apple-system, BlinkMacSystemFont, 'Roboto', sans-serif;
        }

        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
            min-height: 100vh;
            padding: 2rem 1rem;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
        }

        header {
            text-align: center;
            margin-bottom: 2.5rem;
            padding: 2rem;
            background: white;
            border-radius: 16px;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.06);
            position: relative;
            overflow: hidden;
        }

        header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #4f46e5, #0ea5e9, #10b981);
        }

        h1 {
            color: #1e293b;
            font-size: 2.5rem;
            margin-bottom: 0.75rem;
            font-weight: 800;
            letter-spacing: -0.5px;
        }

        .subtitle {
            color: #64748b;
            font-weight: 500;
            font-size: 1.2rem;
            margin-bottom: 1.5rem;
        }

        .controls {
            display: flex;
            justify-content: center;
            gap: 1.2rem;
            margin-bottom: 1rem;
            flex-wrap: wrap;
        }

        .control-btn {
            background: linear-gradient(90deg, #4f46e5, #7c3aed);
            color: white;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 10px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: flex;
            align-items: center;
            gap: 0.75rem;
            box-shadow: 0 4px 15px rgba(79, 70, 229, 0.2);
        }

        .control-btn:hover {
            background: linear-gradient(90deg, #4338ca, #6d28d9);
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(79, 70, 229, 0.3);
        }

        .control-btn:active {
            transform: translateY(-1px);
        }

        .control-btn.zh-btn {
            background: linear-gradient(90deg, #10b981, #0d9488);
        }

        .control-btn.zh-btn:hover {
            background: linear-gradient(90deg, #059669, #0f766e);
            box-shadow: 0 8px 20px rgba(16, 185, 129, 0.3);
        }

        .word-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 2rem;
        }

        .translatable {
            background: white;
            border-radius: 14px;
            padding: 2rem 1.5rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.05);
            position: relative;
            overflow: hidden;
            font-size: 1.5rem;
            font-weight: 700;
            color: #1e293b;
            border: 1px solid rgba(0, 0, 0, 0.03);
        }

        .translatable::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 5px;
            background: linear-gradient(90deg, #4f46e5, #0ea5e9);
            transform: scaleX(0);
            transition: transform 0.4s ease;
            transform-origin: left;
        }

        .translatable:hover {
            transform: translateY(-8px);
            box-shadow: 0 15px 30px rgba(79, 70, 229, 0.15);
        }

        .translatable:hover::before {
            transform: scaleX(1);
        }

        .translatable:active {
            transform: translateY(-4px);
        }

        .translatable.zh {
            color: #0d9488;
        }

        .tooltip {
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%) scale(0.9);
            background-color: #1e293b;
            color: white;
            padding: 0.6rem 1.2rem;
            border-radius: 8px;
            font-size: 0.95rem;
            opacity: 0;
            pointer-events: none;
            transition: all 0.3s ease;
            white-space: nowrap;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .translatable:hover .tooltip {
            opacity: 1;
            transform: translateX(-50%) scale(1);
        }

        .tooltip::after {
            content: '';
            position: absolute;
            top: 100%;
            left: 50%;
            margin-left: -5px;
            border-width: 6px;
            border-style: solid;
            border-color: #1e293b transparent transparent transparent;
        }

        @media (max-width: 768px) {
            .word-grid {
                grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
                gap: 1.5rem;
            }
            
            h1 {
                font-size: 2rem;
            }
            
            .translatable {
                padding: 1.5rem 1rem;
                font-size: 1.3rem;
            }
        }

        @media (max-width: 480px) {
            .word-grid {
                grid-template-columns: 1fr;
            }
            
            .controls {
                flex-direction: column;
                align-items: center;
            }
            
            .control-btn {
                width: 80%;
                justify-content: center;
            }
        }

        /* Login form styles */
        .login-container {
            max-width: 400px;
            margin: 2rem auto;
            padding: 2rem;
            background: white;
            border-radius: 16px;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.06);
        }

        .login-form {
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }

        .form-group {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }

        .form-group label {
            font-weight: 600;
            color: #334155;
        }

        .form-group input {
            padding: 0.75rem;
            border: 1px solid #cbd5e1;
            border-radius: 8px;
            font-size: 1rem;
        }

        .form-group input:focus {
            outline: none;
            border-color: #4f46e5;
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }

        .btn-login {
            background: linear-gradient(90deg, #4f46e5, #7c3aed);
            color: white;
            border: none;
            padding: 0.75rem;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .btn-login:hover {
            background: linear-gradient(90deg, #4338ca, #6d28d9);
            transform: translateY(-2px);
        }

        /* Add word form styles */
        .add-word-container {
            max-width: 500px;
            margin: 2rem auto;
            padding: 2rem;
            background: white;
            border-radius: 16px;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.06);
            display: none;
        }

        .add-word-form {
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }

        .form-row {
            display: flex;
            gap: 1rem;
        }

        .form-row .form-group {
            flex: 1;
        }

        .btn-add-word {
            background: linear-gradient(90deg, #10b981, #0d9488);
            color: white;
            border: none;
            padding: 0.75rem;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .btn-add-word:hover {
            background: linear-gradient(90deg, #059669, #0f766e);
            transform: translateY(-2px);
        }

        /* Batch delete styles */
        .batch-delete-container {
            max-width: 500px;
            margin: 2rem auto;
            padding: 2rem;
            background: white;
            border-radius: 16px;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.06);
            display: none;
        }

        .selected-words {
            margin: 1rem 0;
            padding: 1rem;
            background: #f1f5f9;
            border-radius: 8px;
            max-height: 200px;
            overflow-y: auto;
        }

        .selected-word-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.5rem;
            border-bottom: 1px solid #e2e8f0;
        }

        .btn-batch-delete {
            background: linear-gradient(90deg, #ef4444, #dc2626);
            color: white;
            border: none;
            padding: 0.75rem;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .btn-batch-delete:hover {
            background: linear-gradient(90deg, #dc2626, #b91c1c);
            transform: translateY(-2px);
        }

        /* Navigation */
        .nav-buttons {
            display: flex;
            justify-content: center;
            gap: 1rem;
            margin: 1rem 0;
        }

        .nav-btn {
            background: #e2e8f0;
            color: #334155;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .nav-btn.active {
            background: #4f46e5;
            color: white;
        }

        .nav-btn:hover:not(.active) {
            background: #cbd5e1;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>英语单词学习卡</h1>
            <p class="subtitle">点击单词切换中英文显示</p>
            <div class="controls">
                <button class="control-btn en-btn" id="showAllEn">
                    <i class="fa fa-language"></i> 全部显示英文
                </button>
                <button class="control-btn zh-btn" id="showAllZh">
                    <i class="fa fa-font"></i> 全部显示中文
                </button>
            </div>
        </header>

        <!-- Login Form -->
        <div class="login-container" id="loginContainer">
            <h2 style="text-align: center; margin-bottom: 1.5rem;">用户登录</h2>
            <form class="login-form" id="loginForm">
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" name="username" required>
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" name="password" required>
                </div>
                <button type="submit" class="btn-login">登录</button>
            </form>
        </div>

        <!-- Navigation Buttons -->
        <div class="nav-buttons" id="navButtons" style="display: none;">
            <button class="nav-btn active" data-target="words">单词列表</button>
            <button class="nav-btn" data-target="add">添加单词</button>
            <button class="nav-btn" data-target="batch">批量删除</button>
        </div>

        <!-- Words Grid -->
        <div class="word-grid" id="wordsContainer">
            <!-- Words will be loaded here dynamically -->
        </div>

        <!-- Add Word Form -->
        <div class="add-word-container" id="addWordContainer">
            <h2 style="text-align: center; margin-bottom: 1.5rem;">添加新单词</h2>
            <form class="add-word-form" id="addWordForm">
                <div class="form-row">
                    <div class="form-group">
                        <label for="english">英文单词</label>
                        <input type="text" id="english" name="english" required>
                    </div>
                    <div class="form-group">
                        <label for="chinese">中文意思</label>
                        <input type="text" id="chinese" name="chinese" required>
                    </div>
                </div>
                <button type="submit" class="btn-add-word">添加单词</button>
            </form>
        </div>

        <!-- Batch Delete -->
        <div class="batch-delete-container" id="batchDeleteContainer">
            <h2 style="text-align: center; margin-bottom: 1.5rem;">批量删除单词</h2>
            <div class="selected-words" id="selectedWords">
                <!-- Selected words will appear here -->
            </div>
            <button class="btn-batch-delete" id="batchDeleteBtn">删除选中的单词</button>
        </div>
    </div>

    <script>
        // Global variables
        let isLoggedIn = false;
        let wordsData = [];
        let selectedWords = [];

        // DOM Elements
        const loginContainer = document.getElementById('loginContainer');
        const navButtons = document.getElementById('navButtons');
        const wordsContainer = document.getElementById('wordsContainer');
        const addWordContainer = document.getElementById('addWordContainer');
        const batchDeleteContainer = document.getElementById('batchDeleteContainer');
        const selectedWordsContainer = document.getElementById('selectedWords');

        // Event Listeners
        document.addEventListener('DOMContentLoaded', function() {
            // Login form submission
            document.getElementById('loginForm').addEventListener('submit', handleLogin);
            
            // Add word form submission
            document.getElementById('addWordForm').addEventListener('submit', handleAddWord);
            
            // Batch delete button
            document.getElementById('batchDeleteBtn').addEventListener('click', handleBatchDelete);
            
            // Navigation buttons
            document.querySelectorAll('.nav-btn').forEach(button => {
                button.addEventListener('click', function() {
                    // Update active button
                    document.querySelectorAll('.nav-btn').forEach(btn => btn.classList.remove('active'));
                    this.classList.add('active');
                    
                    // Show/hide containers
                    const target = this.getAttribute('data-target');
                    wordsContainer.style.display = target === 'words' ? 'grid' : 'none';
                    addWordContainer.style.display = target === 'add' ? 'block' : 'none';
                    batchDeleteContainer.style.display = target === 'batch' ? 'block' : 'none';
                });
            });
            
            // Control buttons for showing all words
            document.getElementById('showAllEn').addEventListener('click', showAllEnglish);
            document.getElementById('showAllZh').addEventListener('click', showAllChinese);
        });

        // Handle login
        function handleLogin(e) {
            e.preventDefault();
            
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            fetch('/api/login', {
                method: 'POST',
                body: new FormData(e.target)
            })
            .then(response => {
                if (response.ok) {
                    return response.text();
                } else {
                    throw new Error('Login failed');
                }
            })
            .then(data => {
                isLoggedIn = true;
                loginContainer.style.display = 'none';
                navButtons.style.display = 'flex';
                wordsContainer.style.display = 'grid';
                loadWords();
            })
            .catch(error => {
                alert('登录失败，请检查用户名和密码');
            });
        }

        // Load words from server
        function loadWords() {
            fetch('/api/words')
            .then(response => response.json())
            .then(data => {
                wordsData = data;
                renderWords(data);
            })
            .catch(error => {
                console.error('Error loading words:', error);
            });
        }

        // Render words to the page
        function renderWords(words) {
            wordsContainer.innerHTML = '';
            
            words.forEach(word => {
                const wordElement = document.createElement('div');
                wordElement.className = 'translatable';
                wordElement.dataset.en = word.english;
                wordElement.dataset.zh = word.chinese;
                
                // Create word content container
                const wordContent = document.createElement('div');
                wordContent.className = 'word-content';
                wordContent.textContent = word.english;
                
                // Create tooltip
                const tooltip = document.createElement('span');
                tooltip.className = 'tooltip';
                tooltip.textContent = '点击切换';
                
                // Create checkbox
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.className = 'word-checkbox';
                checkbox.dataset.english = word.english;
                checkbox.style.position = 'absolute';
                checkbox.style.top = '10px';
                checkbox.style.right = '10px';
                checkbox.style.display = isLoggedIn ? 'block' : 'none';
                
                // Add elements to word container
                wordElement.appendChild(wordContent);
                wordElement.appendChild(tooltip);
                wordElement.appendChild(checkbox);
                
                // Add click event for toggling
                wordElement.addEventListener('click', function(e) {
                    if (e.target.classList.contains('word-checkbox')) return;
                    toggleSingleWord(this);
                });
                
                // Add checkbox event for selection
                checkbox.addEventListener('click', function(e) {
                    e.stopPropagation();
                    const english = this.dataset.english;
                    if (this.checked) {
                        selectedWords.push(english);
                    } else {
                        selectedWords = selectedWords.filter(w => w !== english);
                    }
                    updateSelectedWordsDisplay();
                });
                
                wordsContainer.appendChild(wordElement);
            });
        }

        // Toggle single word display
        function toggleSingleWord(element) {
            const en = element.dataset.en;
            const zh = element.dataset.zh;
            const wordContent = element.querySelector('.word-content');
            
            if (wordContent.textContent === en) {
                wordContent.textContent = zh;
                element.classList.add('zh');
            } else {
                wordContent.textContent = en;
                element.classList.remove('zh');
            }
        }

        // Show all words in English
        function showAllEnglish() {
            document.querySelectorAll('.translatable').forEach(element => {
                const wordContent = element.querySelector('.word-content');
                wordContent.textContent = element.dataset.en;
                element.classList.remove('zh');
            });
        }

        // Show all words in Chinese
        function showAllChinese() {
            document.querySelectorAll('.translatable').forEach(element => {
                const wordContent = element.querySelector('.word-content');
                wordContent.textContent = element.dataset.zh;
                element.classList.add('zh');
            });
        }

        // Handle adding a new word
        function handleAddWord(e) {
            e.preventDefault();
            
            const formData = new FormData(e.target);
            
            fetch('/api/word', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (response.ok) {
                    alert('单词添加成功');
                    e.target.reset();
                    loadWords(); // Reload words to show the new one
                } else {
                    alert('添加单词失败');
                }
            })
            .catch(error => {
                console.error('Error adding word:', error);
                alert('添加单词失败');
            });
        }

        // Handle batch delete
        function handleBatchDelete() {
            if (selectedWords.length === 0) {
                alert('请先选择要删除的单词');
                return;
            }
            
            if (!confirm(`确定要删除选中的 ${selectedWords.length} 个单词吗？`)) {
                return;
            }
            
            // Create URLSearchParams instead of FormData for DELETE request
            const params = new URLSearchParams();
            selectedWords.forEach(word => {
                params.append('english', word);
            });
            
            fetch('/api/words/batch?' + params.toString(), {
                method: 'DELETE'
            })
            .then(response => {
                if (response.ok) {
                    alert('单词删除成功');
                    selectedWords = [];
                    updateSelectedWordsDisplay();
                    loadWords(); // Reload words to reflect deletions
                } else {
                    alert('删除单词失败');
                }
            })
            .catch(error => {
                console.error('Error deleting words:', error);
                alert('删除单词失败');
            });
        }

        // Update selected words display
        function updateSelectedWordsDisplay() {
            selectedWordsContainer.innerHTML = '';
            
            if (selectedWords.length === 0) {
                selectedWordsContainer.innerHTML = '<p>暂无选中的单词</p>';
                return;
            }
            
            selectedWords.forEach(word => {
                const wordObj = wordsData.find(w => w.english === word);
                if (wordObj) {
                    const wordItem = document.createElement('div');
                    wordItem.className = 'selected-word-item';
                    wordItem.innerHTML = `
                        <span>${wordObj.english} - ${wordObj.chinese}</span>
                        <button onclick="removeFromSelection('${word}')">移除</button>
                    `;
                    selectedWordsContainer.appendChild(wordItem);
                }
            });
        }

        // Remove a word from selection
        function removeFromSelection(english) {
            selectedWords = selectedWords.filter(w => w !== english);
            // Also uncheck the checkbox
            document.querySelectorAll(`.word-checkbox[data-english="${english}"]`).forEach(checkbox => {
                checkbox.checked = false;
            });
            updateSelectedWordsDisplay();
        }
    </script>
</body>
</html>